<template>
  <div class="app-container">
    <nabars index="2"></nabars>
    <topIndex style="margin-bottom: 20px" :indexCount="indexCount"></topIndex>
    <div style="display: flex">
      <el-form
        :model="queryParams"
        class="frominfo"
        ref="queryForm"
        size="small"
        :inline="true"
        v-show="showSearch"
        label-width="100px"
      >
        <div class="from-item">
          <el-form-item label="微信名称" prop="wcUserName">
            <el-input
              v-model="queryParams.wcUserName"
              @keyup.enter.native="handleQuery"
              placeholder="请输入好友微信名称"
              clearable
            />
          </el-form-item>

          <el-form-item label="助手名称" prop="nickName">
            <el-input v-model="queryParams.nickName" @keyup.enter.native="handleQuery" placeholder="请输入助手名称"
                      clearable/>
          </el-form-item>

          <el-form-item label="好友所属人员" prop="wcId" v-if="!common">
            <el-select style="width: 120px;" v-if="!qommon"
                       v-model="queryParams.deptId"
                       @change="getDept"
                       placeholder="请选择区域"
                       clearable
            >
              <el-option
                v-for="dict in deptName"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
            <el-autocomplete style="width: 160px;"
                             class="my-autocomplete"
                             v-model="param.lable"
                             :fetch-suggestions="querySearch"
                             placeholder="请输入内容"
                             @select="handleSelect"
            ></el-autocomplete>
            <!-- <el-select
              v-model="queryParams.wcId"
              placeholder="请选择助手"
              clearable
            >
              <el-option
                v-for="dict in userName"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select> -->
            <!-- <el-input v-model="queryParams.wcName" @keyup.enter.native="handleQuery" placeholder="请输入助手微信名称" clearable/> -->
          </el-form-item>
          <el-form-item label="归属地" prop="wcUserRegion">
            <el-input v-model="queryParams.wcUserRegion" @keyup.enter.native="handleQuery"
                      placeholder="请输入好友归属地" clearable/>
          </el-form-item>
          <el-form-item label="聊天时间" prop="loginTime">
            <el-date-picker
              v-model="chatTime"
              style="width: 240px"
              value-format="yyyy-MM-dd"
              type="daterange"
              range-separator="-"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
            ></el-date-picker>
          </el-form-item>
        </div>
        <div class="from-Btn">
          <el-form-item>
            <el-button
              type="primary"
              style="background-color: #0078fb"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
            >查询
            </el-button
            >
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置
            </el-button
            >
          </el-form-item>
        </div>
      </el-form>
      <div class="btnline">
        <div class="addbtn" @click="golink('/friend/add-group')">
          <i class="el-icon-plus"></i><span>群好友添加</span>
        </div>
        <div class="addbtn" @click="golink('/friend/import')">
          <i class="el-icon-plus"></i><span>导入添加</span>
        </div>
      </div>
    </div>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="multiple"
          @click="handleUpdate()"
        >批量绑定
        </el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="wcUserInfoList"
      :header-cell-style="{ background: '#fcfcfd', color: '#000' }"
      @selection-change="handleSelectionChange"
      :border="false"
    >
      <el-table-column type="selection" width="50" align="center"/>
      <el-table-column
        label="微信名称"
        prop="wcUserName"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="最新聊天时间"
        prop="lastChatTime"
        align="center"
        :show-overflow-tooltip="true"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
              parseTime(scope.row.lastChatTime, "{y}-{m}-{d} {h}:{i}:{s}")
            }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="微信ID"
        prop="wcUserId"
        align="center"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="地区/部门" prop="deptName" align="center" :show-overflow-tooltip="true"/>

      <el-table-column
        label="所属营销助手"
        prop="nickName"
        align="center"
        :show-overflow-tooltip="true"
      />

      <el-table-column label="好友标签" prop="friendLabel" align="center" :show-overflow-tooltip="true"/>

      <el-table-column align="center" width="120" class-name="small-padding fixed-width">
        <template slot="header">
          <span>绑定标签</span>
          <el-tooltip class="item" effect="dark" content="点击操作" placement="top">
            <i class="el-icon-warning" style="color:#818e96;"></i>
          </el-tooltip>
        </template>
        <template slot-scope="scope">
          <span style="color:#0078fb;cursor: pointer;" @click="handleUpdate(scope.row)">绑定</span>
        </template>
      </el-table-column>

      <el-table-column
        align="center"
        width="120"
        class-name="small-padding fixed-width"
        style="cursor: pointer"
      >
        <template slot="header">
          <span>好友详情</span>
          <el-tooltip
            class="item"
            effect="dark"
            content="进入查看好友详情"
            placement="top"
          >
            <i class="el-icon-warning" style="color: #818e96"></i>
          </el-tooltip>
        </template>
        <template slot-scope="scope">
          <span
            style="color: #0078fb; cursor: pointer"
            @click="golinks(scope.row.wcUserId)"
          >详情</span
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog title="绑定标签" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="绑定标签" prop="dictLabel">
          <el-select v-model="form.labelId" placeholder="请选择标签" clearable>
            <el-option v-for="dict,index in lableInfo" :key="index" :label="dict.dictLabel" :value="dict.dictCode"/>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import nabars from "../components/nabar.vue";
import mathNum from "../components/daily.js";
import topIndex from "../components/top-index.vue";
import {listDept} from "@/api/system/dept";
import {listWcUser} from "@/api/system/user";
import {groupBind, groupLabel} from "../group/index";

export default {
  name: "WcUserInfo",
  dicts: ["sys_login_status"],
  components: {
    nabars,
    topIndex,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 用户微信表格数据
      wcUserInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      chatTime: [],
      param: {
        wcId: null,
        lable: null,
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        wcId: null,
        deptId: null,
        wcUserName: null,
        nickName: null,
        wcUserRegion: null,
        beginTime: null,
        endTime: null,
      },
      lableInfo: [],
      form: {labelId: null, dataId: null, type: 'friend_label'},
      common: false,
      qommon: false,
      indexCount: [
        {name: "今日新增好友", num: 0, type: 0, bili: 0},
        {name: "今日入网", num: 0, type: 0, bili: 0},
        {name: "新增好友入网", num: 0, type: 0, bili: 0},
      ],
      addType: true,
      userOptions: [],
      userParams: {
        pageNum: 1,
        pageSize: 9999,
        deptId: undefined,
      },
      deptName: [],
      userName: [],
    };
  },
  created() {
    if (this.$store.state.user.roles.includes("common")) {
      this.common = true;
      this.qommon = true;
    }
    if (this.$store.state.user.roles.includes("qxleader")) {
      this.common = false;
      this.qommon = true;
    }
    if (!this.qommon) {
      var deptName = []
      listDept().then(response => {
        if (response.code == 200) {
          response.data.forEach((item) => {
            deptName.push({value: item.deptId, label: item.deptName})
          })
          this.deptName = deptName
        }
      });
    } else {
      var userName = []
      this.userParams = null
      listWcAssist(this.userParams).then((res) => {
        if (res["success"]) {
          const dt = res["data"];
          dt["records"].forEach((element) => {
            //userName.push({value:element.wcId,label:element.wcName})
            userName.push({value: element.wcName, label: element.wcId})
          });
        }
        this.userName = userName
      });
    }

  },
  mounted() {
    this.friendLabel();
    this.getList();
    this.init();
  },
  methods: {
    init() {
      getInterNet().then((res) => {
        if (res.code == 200) {
          if (res.data) {
            this.indexCount[2].type = mathNum(
              res.data.new_size,
              res.data.old_size
            ).split("_")[0];
            this.indexCount[2].bili = mathNum(
              res.data.new_size,
              res.data.old_size
            ).split("_")[1];
            this.indexCount[2].num = res.data.new_size;
          }
        }
      });
      getUserInternet().then((res) => {
        if (res.code == 200) {
          if (res.data) {
            this.indexCount[1].type = mathNum(
              res.data.new_size,
              res.data.old_size
            ).split("_")[0];
            this.indexCount[1].bili = mathNum(
              res.data.new_size,
              res.data.old_size
            ).split("_")[1];
            this.indexCount[1].num = res.data.new_size;
          }
        }
      });
      getAddFriend().then((res) => {
        if (res.code == 200) {
          if (res.data) {
            this.indexCount[0].type = mathNum(
              res.data.new_size,
              res.data.old_size
            ).split("_")[0];
            this.indexCount[0].bili = mathNum(
              res.data.new_size,
              res.data.old_size
            ).split("_")[1];
            this.indexCount[0].num = res.data.new_size;
          }
        }
      });
    },
    getDept(value) {
      if (value != '') {
        this.userParams.deptId = value
        this.queryParams.wcId = null
        var userName = []
        listWcUser(this.userParams).then((res) => {
          //console.log(res)
          if (res["code"] == 200) {
            const dt = res["rows"];
            dt.forEach((element) => {
              if (this.userParams.deptId == 100) {
                if (element.deptId == 100 && element.wcId != '' && element.wcId != null) {
                  // userName.push({value:element.wcId,label:element.nickName})
                  userName.push({value: element.nickName, label: element.wcId})
                }
              } else if (element.wcId != '' && element.wcId != null) {
                // userName.push({value:element.wcId,label:element.nickName})
                userName.push({value: element.nickName, label: element.wcId})
              }
            });
          }
          this.userName = userName
        });
      }

    },
    async getAssist() {
      await listWcAssist(this.query).then((res) => {
        if (res["success"]) {
          const dt = res["data"];
          this.totals = dt["total"];
          dt["records"].forEach((element) => {
            element.remark = false;
          });
          if (this.$store.state.user.roles.includes("common")) {
            this.addType = dt["records"][0].canCreateTask;
          }
        }
      });
    },
    golink(url) {
      this.getAssist().then((res) => {
        if (this.addType) {
          this.$router.push({path: url}).catch(() => {
          });
        } else {
          this.$message({
            message: "添加好友已经超过最高限制！",
            type: "warning",
          });
        }
      });
    },
    golinks(wxid) {
      this.$router
        .push({path: "/friend/detial/", name: "friendinfo", query: {wxid}})
        .catch(() => {
        });
    },
    /** 查询用户微信列表 */
    getList() {
      this.loading = true;
      var param = this.queryParams
      if (this.param.wcId != null) {
        param.wcId = this.param.wcId
      }

      listWcUserInfo(param).then((res) => {
        if (res["success"]) {
          const dt = res["data"];
          this.total = dt["total"];
          this.wcUserInfoList = dt["records"];
        }
        this.loading = false;
      });
      setTimeout(() => {
        this.loading = false;
      }, 2000);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        assistId: null,
        wcId: null,
        wcName: null,
        wcNumber: null,
        wcImg: null,
        wcPhone: null,
        region: null,
        loginTime: null,
        loginState: null,
        remark: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.beginTime = null;
      this.queryParams.endTime = null;
      if (this.chatTime != "" && this.chatTime != null) {
        this.queryParams.beginTime = this.chatTime[0] + " 00:00:00";
        this.queryParams.endTime = this.chatTime[1] + " 23:59:59";
      }
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.chatTime = [];
      this.queryParams.wcId = null
      this.queryParams.deptId = null
      this.param.wcId = null
      this.param.lable = null
      this.userParams = {
        pageNum: 1,
        pageSize: 9999,
        deptId: undefined,
      }
      this.handleQuery();
    },
    friendLabel() {
      friendLabel().then(res => {
        //console.log(res)
        if (res.code == 200) {
          this.lableInfo = res.data
        }
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      //console.log(row)
      this.form = {labelId: null, dataId: null, type: 'friend_label'}
      this.open = true
      if (row) {
        this.form.dataId = row.id
      }
    },
    /** 提交按钮 */
    submitForm() {
      this.form.dataId = this.form.dataId || this.ids.join(',');
      this.$refs["form"].validate(valid => {
        if (valid) {
          groupBind(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.form.dataId = null;
            this.open = false;
            this.getList();
          });
        }
      });
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      //console.log('ids = ',this.ids)
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    querySearch(queryString, cb) {
      var restaurants = this.userName;
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0);
      };
    },
    handleSelect(item) {
      this.param.lable = item.value
      this.param.wcId = item.label
    },
  },
};

/** js请求 调用 */

// 查询用户微信列表
export function listWcUserInfo(query) {
  return request({
    url: "/arbit/wcfriend_info/page",
    method: "get",
    params: query,
  });
}

// 获取今日新增好友在网数量
export function getInterNet(data) {
  return request({
    url: "/arbit/wcfriend_info/new_friend_olin",
    method: "get",
    data: data,
  });
}

// 获取今日新增好友数量
export function getAddFriend(data) {
  return request({
    url: "/arbit/wcfriend_info/new_friend",
    method: "get",
    data: data,
  });
}

// 获取好友在网数量
export function getUserInternet(data) {
  return request({
    url: "/arbit/wcfriend_info/data_friend_olin",
    method: "get",
    data: data,
  });
}

//获取所有好友标签
export function friendLabel() {
  return request({
    url: '/label/relevance/type/friend_label',
    method: 'GET',
  })
}

// 查询助手信息列表
export function listWcAssist(query) {
  return request({
    url: "/arbit/wcuser_info/page",
    method: "get",
    params: query,
  });
}
</script>
<style scoped lang="scss">
.app-container {
  background-color: #f6f9fb;
}

.my-autocomplete {
  width: 160px;
}

.frominfo {
  display: flex;
  background-color: #fff;
  padding: 10px;
  padding-bottom: 0;
  margin-bottom: 20px;
  width: 90%;

  .from-item {
    display: flex;
    flex-wrap: wrap;
    width: 85%;
  }

  .from-Btn {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    width: 20%;
  }
}

.btnline {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-between;
  width: 10%;
  padding: 5px 0 25px 0;

  .addbtn {
    width: 100px;
    border-radius: 5px;
    background-color: #0078fb;
    border-color: #0078fb;
    font-size: 15px;
    text-align: center;
    height: 40px;
    line-height: 40px;
    color: #fff;
    cursor: pointer;
  }
}
</style>
